package demo09StackQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 11 - 02
 * Time:18:48
 */

/***
 * 1.循环队列：
 * front:
 * rear:代表尾指针，当前可以存放元素的下标
 * (1)循环队列为空：front == rear
 * (2)循环队列为满：(rear + 1) % len == front
 *
 * 2.对于front+ 1 和rear + 1都会面临越界问题：
 * 解决方案：
 * 牺牲一个空间来判断是否为满；
 * 根据当前rear的洗衣歌指针是否是front来进行判满
 *
 * 3.循环队列为满：(rear + 1) % len == front
 */

public class MyCycleQueue {
    private int front;
    private int rear;//队尾：表示当前可以存放数据元素的下标
    private int[] elem;

    //1.构造器，设置队列长度为k
    public MyCycleQueue(int k){
        this.elem = new int[k];
        this.front = 0;
        this.rear = 0;
    }
    //2.入队
    public boolean enQueue(int value){
        if(isFull()){
            return  false;
        }
        //将元素放到数组的rear下标，rear++
        this.elem[rear] = value;
        this.rear = (this.rear + 1) % this.elem.length;
        return true;
    }
    //3.出队
    public boolean deQueue(){
        if(isEmpty()){
            return  false;
        }
        //只需要修改front的下标
        this.front = (this.front + 1) % this.elem.length;
        return  true;

    }
    //4.获取队头元素
    public int front(){
        if(isEmpty()){
            return  -1;
        }
        int ret = this.elem[this.front];
        return ret;
    }
    //5.获取队尾元素
    public int rear(){
        if(isEmpty()){
            return -1;
        }
        int index = -1;
        if(this.rear == 0){
            index = this.elem.length - 1;
        }else{
            index = this.rear - 1;
        }
        return this.elem[index];
    }
    //6.判空
    public boolean isEmpty(){
        return front == rear;
    }
    //7.判满
    public boolean isFull() {
        return ((this.rear + 1) % this.elem.length == this.front);

    }
}
